import logging
import json
from common.card_login_history import db as cardLogin_db
from common.utils.decorator import response_wrapper
from common.utils.aes_crypt import aes_encrypt_str
from common.utils.tz import utc_to_local_str
from django.views.decorators.http import require_POST, require_GET

_LOGGER = logging.getLogger('hydra')

@require_GET
@response_wrapper
def get_cardLoginHistory(req):
    query_dct = req.GET.dict()
    data = cardLogin_db.get_card_login_history(query_dct['id'])
    data['id'] = aes_encrypt_str(data['id'])
    _LOGGER.info('get_cardLoginHistory: %s', query_dct['id'])
    return data

@require_POST
@response_wrapper
def save_cardLoginHistory(req):
    _LOGGER.info('record_match_order: %s', req.body)
    d = json.loads(req.body)
    if d :
        data = cardLogin_db.log_card_history(d)
        return  { "Id" :data.id, "CardId": data.card_id, "IsLogin" : d["IsLogin"], "LoginTime": data.login_time , "LogoutTime": data.logout_time  }
    else:
        return {}

@require_GET
@response_wrapper
def get_card_login_history(req):
    query_dct = req.GET.dict()
    items, total_count = cardLogin_db.get_card_login_history(query_dct)
    resp_items = []
    for item in items:
        data = item.as_dict()
        data['id'] = data['id']
        data['card_id'] = data['card_id']
        data['login_time'] = utc_to_local_str(data['login_time'])
        data['logout_time'] = utc_to_local_str(data['logout_time']) if data['logout_time'] else ''
        resp_items.append(data)
    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'size': len(resp_items), 'total_count': total_count}
